package online.siwu.memorycards

import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.KeyEvent
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import kotlinx.android.synthetic.main.activity_eidt.*
import java.io.File


class EditActivity : AppCompatActivity() {
    private val GD = GlobalData

    var num = 0
    var strNow = ""

    var file: File? = null

    private var list = arrayListOf<String>()
    private var adapter: ArrayAdapter<String>? = null


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_eidt)

        file = File(filesDir, "piles110.np")

        btDafult.setOnClickListener(oclDefault)
        btSave.setOnClickListener(oclSave)
        btReset.setOnClickListener(oclReset)
        btOK.setOnClickListener(oclOK)
        btBack.setOnClickListener(oclBack)

        for (i in 0..109) {
            list.add("  ${GD.int2str110(i)}  ")
        }

        adapter = ArrayAdapter(this, R.layout.spinner_font, list)
        spinner.adapter = adapter
        spinner.onItemSelectedListener = IslSpinner()

    }

    // copy file 从 assets 到 data
    // 转到StartActivity
    private val oclDefault = View.OnClickListener {

        GD.copy2Data(file!!, assets.open("piles110.np"))

        gotoActivity<StartActivity>()
    }

    // 把 arr 保存到文件
    private val oclSave = View.OnClickListener {

        GD.writeFile(file!!)

        gotoActivity<CodeListActivity>()
    }

    // 还原 正在编辑的Text
    private val oclReset = View.OnClickListener {

        etCode.setText(GD.arrCode[num])
    }

    // text 赋值到 arr，如果Text非空
    private val oclOK = View.OnClickListener {

        val str = etCode.text.toString()
        if (str == "")
            toast("非法编码！")
        else
            GD.arrCode[num] = str
    }

    // 按back 转到 CodeList
    private val oclBack = View.OnClickListener {

        exitBack()
    }

    // 同上
    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK)
            exitBack()

        return false
    }

    // 同上
    private fun exitBack() {
        gotoActivity<CodeListActivity>()
    }

    //内部类
    //spinner监听
    inner class IslSpinner : AdapterView.OnItemSelectedListener {

        override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
            val str = parent!!.getItemIdAtPosition(position).toString()
            num = GD.str2Int(str)
            strNow = GD.arrCode[num].toString()
            etCode.setText(strNow)
        }

        override fun onNothingSelected(parent: AdapterView<*>?) {}
    }

}
